/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import java.util.Date;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.CustomerNursingPlan;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(CustomerNursingPlan.class)
@Component
public class CustomerNursingPlanRepository extends BaseRepository<CustomerNursingPlan> {

	@Autowired
	protected NursingService nursingService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(CustomerNursingPlan.class);
	}

	@Override
	@JsonApiSave
	public CustomerNursingPlan save(CustomerNursingPlan record) {//
		//验证计划时间是今天以后
		Date now = new Date();
		Integer weekIndex = CommonUtil.getWeekIndexFromSun(now);
		Integer yearTab = now.getYear() + 1900;
		Integer weekTab = CommonUtil.getWeek(now);
		if ((record.getYearTab() < yearTab)
				|| (yearTab.equals(record.getYearTab()) && record.getWeekIndex() < weekIndex)
				|| (yearTab.equals(record.getYearTab()) && weekIndex.equals(record.getWeekIndex())&& record.getWeekTab() <= weekTab)) {
			record.setErrcode(11);// 时间在之前
			throw new BusinessException(null, CommonConstants.ERROR_CODE.TIME_ERROR.label(), null);
		}
		//nursingService.deletePlanDetailByRecord(record);// 删除所传周 的detail   如为当前周至删除今天以后的
		nursingService.deletePlanDayDetailByRecord(record);  //删除所传那天的  周计划或者日计划
		record = super.save(record);
		// 判断 是否复制 产生模版
		if (record.getRemark() != null && !"".equals(record.getRemark())) {
			if ("copy".equals(record.getRemark()) && record.getDetails() != null && record.getDetails().size() != 0) {
				nursingService.deletePlanItem(record);//删除模版
				nursingService.createPlanItem(record);// 产生模版
				nursingService.copyPlanToNextWeeks(record,3);// 复制到后三周
			}
		}
		return record;
	}

}
